﻿using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Law.Dto;
using Com.JunCaiSoft.Law.Entity;
using Com.JunCaiSoft.Law.IDao;
using Com.JunCaiSoft.Law.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Law.Controllers
{
    /// <summary>
    /// 保全信息管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class PreservationController : BaseController<PreservationView, PreservationItem, Preservation, Guid>
    {
        public PreservationController(IPreservationDao caseDao) : base(caseDao)
        {

        }
        /// <summary>
        /// 按保全ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<Preservation>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按保全ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<Preservation>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" p.Id,
	                             p.Num,
	                             p.NumCode,
	                             p.CaseCode,
	                             pj.Name CaseProject,
	                             c.PreserveStatus,
	                             pt.Name BranchCompany,
	                             c.CaseStatus,
	                             p.Amount,
	                             p.NoticeDept,
	                             p.NoticePerson,
	                             p.Document,
	                             u.RealName ,
	                             p.CreateTime  ";

                var tables = @" Preservation p
	                            left join CaseMain c on p.CaseMainInfo = c.Id
	                            left join Project pj on c.CaseProject = pj.Id
                                left join Partment pt on pj.Partment = pt.Id
	                            left join [User] u on p.RegistOperator = u.Id ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    where += " AND pj.Name like @CaseCodeOrProjectName OR p.CaseCode like @CaseCodeOrProjectName ";

                    SqlParameter QueryPreservation = new SqlParameter("@CaseCodeOrProjectName", "%" + keyword + "%");

                    bankParams.Add(QueryPreservation);

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<PreservationItemDto>(pageIndex, pageSize, " p.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<PreservationItem>();

                var itemList = new List<PreservationItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<PreservationItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建保全信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(PreservationView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<Preservation>();
                var result = await DaoAsync.InsertAsync(saveone);

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新保全信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<PreservationView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<Preservation>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
    }
}
